<template>
  <div class="logistics-tracking-container">
    <!-- 页面标题 -->
    <el-page-header 
      @back="handleBack" 
      content="物流跟踪管理"
      class="page-header"
    />
    
    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input 
            v-model="searchQuery"
            placeholder="请输入物流单号" 
            clearable
            size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-button 
            type="primary" 
            @click="handleSearch"
            size="small"
            class="search-btn"
          >
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button 
            @click="resetFilters"
            size="small"
            class="reset-btn"
          >
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 物流信息表格 -->
    <el-card class="table-card">
      <el-table 
        :data="logisticsList" 
        border 
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{background: '#f5f7fa', color: '#303133'}"
      >
        <el-table-column 
          prop="logisticsNo" 
          label="物流单号" 
          width="160"
          align="center"
        />
        <el-table-column 
          prop="trackingNode" 
          label="物流节点" 
          width="180"
          align="center"
        >
          <!-- 表格中显示中文节点 -->
          <template #default="scope">
            {{ formatTrackingNode(scope.row.trackingNode) }}
          </template>
        </el-table-column>
        <el-table-column 
          prop="trackingLocation" 
          label="当前位置" 
          min-width="140"
          align="center"
        />
        <el-table-column 
          prop="trackingTime" 
          label="更新时间" 
          width="380"
          align="center"
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.trackingTime) }}
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="160"
          align="center"
        >
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewDetails(scope.row)"
              class="view-btn"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
      <el-pagination
        :page-size="params.pageSize"
        :total="params.recordCount"
        v-model:current-page="params.pageNum"
        @current-change="handleCurrentChange"
        @prev-click="prevPage" 
        @next-click="nextPage"
        layout="total,prev,pager,next"
      />
      </div>
    </el-card>
    
    <!-- 物流详情弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="物流详情" 
      :width="dialogWidth"
      :before-close="handleDialogClose"
    >
      <div class="logistics-details">
        <el-descriptions column="1" border>
          <el-descriptions-item label="物流ID">{{ currentLogistics.trackingId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="订单ID">{{ currentLogistics.orderId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="合作伙伴ID">{{ currentLogistics.partnerId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="物流单号">{{ currentLogistics.logisticsNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="负责人电话">
            <a :href="`tel:${currentLogistics.contact}`" v-if="currentLogistics.contact">{{ currentLogistics.contact }}</a>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="当前节点">
            <!-- 详情中显示中文节点 -->
            {{ formatTrackingNode(currentLogistics.trackingNode) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="当前位置">{{ currentLogistics.trackingLocation || '-' }}</el-descriptions-item>
          <el-descriptions-item label="物流描述">{{ currentLogistics.trackingDesc || '-' }}</el-descriptions-item>
          <el-descriptions-item label="最后更新时间">
            {{ formatDateTime(currentLogistics.trackingTime) || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentLogistics.createTime) || '-' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 物流时间线 -->
        <div class="timeline-container">
          <h3 class="timeline-title">物流轨迹</h3>
          <el-timeline>
            <el-timeline-item 
              v-for="(item, index) in currentLogistics.logisticsTrackingLine|| []" 
              :key="index"
              :timestamp="formatDateTime(item.time)"
              :color="index === 0 ? 'primary' : 'gray'"
              :icon="index === 0 ? Clock : null"
            >
              <el-card>
                <!-- 时间线中显示中文节点 -->
                <h4>{{ formatTrackingNode(item.trackingNode) }}</h4>
                <p>{{ item.trackingLocation }}</p>
                <p class="timeline-desc">{{ item.trackingDesc }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Clock } from '@element-plus/icons-vue';
import { queryPage } from '../../api/logistics';
import { useRouter } from 'vue-router';

// 在setup中获取router实例
const router = useRouter();

// 状态定义
const loading = ref(true);
const logisticsList = ref([]);
const params = ref({
  pageNum: 1,
  pageSize: 5,
  recordCount: 0,
  pageCount: 0
});
const dialogVisible = ref(false);
const dialogWidth = ref('700px');
const currentLogistics = ref({});

// 筛选条件
const searchQuery=ref("")

// 生命周期钩子
onMounted(() => {
  searchPage()
});

// 方法定义
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  
  // 创建日期对象（兼容不同格式的输入）
  const date = new Date(dateString);
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) return dateString;
  
  // 提取年月日时分秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  // 格式化并返回
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 新增：物流节点数字转中文的方法
const formatTrackingNode = (nodeValue) => {
  // 如果没有值，返回空
  if (nodeValue === undefined || nodeValue === null) return '';
  
  // 将值转换为数字（处理字符串形式的数字）
  const nodeNum = Number(nodeValue);
  
  // 定义节点映射关系
  const nodeMap = {
    1: '已揽件',
    2: '运输中',
    3: '到达中转站',
    4: '已派送',
    5: '已签收',
    6: '异常'
  };
  
  // 返回对应的中文，没有匹配到则返回原始值
  return nodeMap[nodeNum] || nodeValue;
};

const handleSearch = () => {
  params.value.pageNum = 1; 
  searchPage();
  ElMessage.success('搜索成功');
};

const resetFilters = () => {
   searchQuery.value=""
  params.value.pageNum =1 ;
  searchPage();
};

const handleCurrentChange = (val) => {
  params.value.pageNum= val;
  searchPage();
};

const handleViewDetails = (row) => {
  currentLogistics.value = { ...row };
  dialogVisible.value = true;
};

const handleDialogClose = () => {
  dialogVisible.value = false;
  currentLogistics.value = {};
};

const handleBack = () => {
  router.back();
  ElMessage.info('返回上一页');
};

function searchPage(){
  queryPage(searchQuery.value,params.value.pageNum,params.value.pageSize)
    .then(response => {
      console.log(response);
      logisticsList.value = response.list;
      params.value = response.pager;
      loading.value=false
    })
    .catch(error => {
      console.error('初始化查询失败:', error);
    });
}
</script>

<style scoped>
.logistics-tracking-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.search-btn {
  margin-right: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.logistics-details {
  padding: 10px 0;
}

.timeline-container {
  margin-top: 20px;
}

.timeline-title {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.timeline-desc {
  color: #606266;
  margin-top: 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dialog-width {
    width: 90% !important;
  }
  
  .el-row {
    flex-wrap: wrap;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .el-col:last-child {
    width: 100% !important;
  }
}
</style>
